<template>
  <el-container class="layout-container-demo" style="height: 100vh">
    <el-dialog v-model="dialogFormVisible" title="优惠卷" width="600" style="margin-top: 30px;">
      <el-form :model="couponForm" ref="couponFormRef" :rules="rules" status-icon>
        <el-form-item label="所属店铺id" :label-width="formLabelWidth" prop="shopId">
          <el-input v-model="couponForm.shopId" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="有效期" :label-width="formLabelWidth" prop="time">
          <!-- <el-input v-model="couponForm.time" autocomplete="off" /> -->
          <el-date-picker v-model="date" type="datetimerange" range-separator="To" start-placeholder="Start date"
            end-placeholder="End date" />
        </el-form-item>
        <el-form-item label="规则类型" :label-width="formLabelWidth" prop="rule">
          <el-input v-model="couponForm.rule" autocomplete="off" disabled style="width: 280px;" />
          <el-radio-group v-model="couponForm.rule">
            <el-radio-button label="1">免单</el-radio-button>
            <el-radio-button label="2">折扣</el-radio-button>
            <el-radio-button label="3">满减</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="规则细节" :label-width="formLabelWidth" prop="ruleDetail">
          <el-input v-model="couponForm.ruleDetail" autocomplete="off" disabled style="width: 150px;" />
          <div v-if="couponForm.rule == '2'" style="display: flex;">
            <el-input v-model="couponForm.ruleDetail" style="width: 295px;" />
            <div style="">折</div>
          </div>
          <div v-if="couponForm.rule == '3'" style="display: flex;">
            <div>满</div>
            <el-input v-model="reduction1" style="width: 140px;" />
            <div>减</div>
            <el-input v-model="reduction2" style="width: 140px;" />
          </div>
        </el-form-item>
        <el-form-item label="用户" :label-width="formLabelWidth" prop="userList">
          <el-input v-model="couponForm.userList" autocomplete="off" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="resetForm(couponFormRef)">
            取消
          </el-button>
          <el-button type="primary" @click="CUCoupon(couponFormRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>
  
<script lang="ts" setup>
import { createCouponByShopIdAndJwt, updateCouponByIdAndJwt, getCouponByIdAndJwt } from "../../api/coupon/"
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ToDate, ToString } from '../../util/DateUtil.ts'
import { useRouter } from 'vue-router'
const router = useRouter();

// // 打开优惠卷选择页
// let addressRef = ref()
// const openAddressChoose = () => {
//   //子组件方法
//   addressRef.value.openDialog();
// }

const shopId = router.currentRoute.value.query.shopId;

// 要编辑的商品的id
// !当为0时调用新建商品方法 非0是调用编辑商品方法
const couponId = ref(0);
const shopIdd = ref(0);
//打开本CouponCU页
const dialogFormVisible = ref(false)
const openDialog = (id: number, shopId: number) => {
  dialogFormVisible.value = true
  couponId.value = id
  shopIdd.value = shopId
}
defineExpose({
  openDialog
})

// 指定字段宽度属性
const formLabelWidth = '100px'

// 商品表单
interface couponType {
  id: number,
  shopId: any,
  rule: string,
  ruleDetail: string,
  time: string,
  userList: string
}
const couponFormRef = ref<FormInstance>()
//创建商品表单数据
let couponForm = reactive<couponType>({
  id: 0,
  shopId: shopId,
  rule: '',
  ruleDetail: '',
  time: '',
  userList: '0',
})
const rules = reactive<FormRules<couponType>>({
  shopId: [
    { required: true, message: '请输入商品标题', trigger: 'blur' },
    // { type: 'number', min: 1, max: 100, message: '长度1-100', trigger: 'blur' },
  ],
  rule: [
    { required: true, message: '请选择规则类型', trigger: 'blur' },
    { type: 'string', min: 1, max: 100, message: '文本长度1-100', trigger: 'blur' },
  ],
  // ruleDetail: [
  //   { required: true, message: '请选择规则细节', trigger: 'blur' },
  //   { type: 'string', min: 1, max: 100, message: '文本长度1-100', trigger: 'blur' },
  // ],
  // time: [
  //   { required: true, message: '请选择有效期', trigger: 'blur' },
  //   { type: 'string', min: 1, max: 100, message: '文本长度1-100', trigger: 'blur' },
  // ],
  userList: [
    { required: true, message: '请选择有效用户', trigger: 'blur' },
    { type: 'string', min: 1, max: 100, message: '文本长度1-100', trigger: 'blur' },
  ]
})

// 时间选择器数据
const date = ref<[Date, Date]>([
  new Date(),
  new Date(),
])
const reduction1 = ref(0);
const reduction2 = ref(0);

// 根据选择的优惠卷获取值添加优惠卷页面
// 优惠卷查时间并更改日期选择器的值
watch(couponId, (newVal, oldVal) => {
  if (couponId.value != 0) {
    const getCommodityByIdResult = getCouponByIdAndJwt({ id: newVal })
    getCommodityByIdResult.then((res) => {
      if (res.code === 200) {
        //更改表单数据
        // couponForm = reactive<couponType>(res.data)
        couponForm.id = res.data.id
        couponForm.rule = res.data.rule
        couponForm.ruleDetail = res.data.ruleDetail
        // couponForm.shopId = 
        couponForm.time = res.data.time
        couponForm.userList = res.data.userList

        //更改Date选择器 
        const str = res.data.time
        const dateList = str.split("——");
        const startStr: string = dateList[0]
        const endStr: string = dateList[1]
        const start: Date = ToDate(startStr);
        const end: Date = ToDate(endStr);
        date.value[0] = start
        date.value[1] = end
      } else {
        return ElMessage({
          showClose: true,
          message: res.message,
          type: 'error',
        })
      }

      // 更改满减框
      if (res.data.rule == 3) {
        const reductionList = res.data.ruleDetail.split("-")
        reduction1.value = reductionList[0]
        reduction2.value = reductionList[1]
      }


    })
  }
}, {
  // 深度监听
  deep: true,
  // 监听对象初次加载时也调用一次方法体
  // immediate: true
})

// 根据选择的日期改表单有效期值
watch(date, (newVal, oldVal) => {
  const startStr = ToString(newVal[0])
  const endStr = ToString(newVal[1])
  couponForm.time = startStr + '——' + endStr
}, {
  // 深度监听
  deep: true,
  // 监听对象初次加载时也调用一次方法体
  // immediate: true
})

// 根据填写的满减框更改表单
watch([reduction1, reduction2], (newVal, oldVal) => {
  couponForm.ruleDetail = newVal[0] + "-" + newVal[1]
}, {
  // 深度监听
  deep: true,
  // 监听对象初次加载时也调用一次方法体
  // immediate: true
})

// CU优惠卷
const CUCoupon = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (couponForm.rule == "3") {
        if (reduction1.value < reduction2.value || reduction1.value == 0 || reduction2.value == 0 || reduction1.value == null || reduction2.value == null) {
          return ElMessage({
            showClose: true,
            message: "满减数值有误",
            type: 'error',
          })
        }
      }
      if (couponId.value == 0) {
        const createCouponByShopIdAndJwtResult = createCouponByShopIdAndJwt(couponForm)
        createCouponByShopIdAndJwtResult.then((res) => {
          if (res.code === 200) {
            dialogFormVisible.value = false
            return ElMessage({
              showClose: true,
              message: "创建商品成功",
              type: 'success',
            })
          } else {
            return ElMessage({
              showClose: true,
              message: res.message,
              type: 'error',
            })
          }
        })
      } else {
        const updateCouponByIdAndJwtResult = updateCouponByIdAndJwt(couponForm)
        updateCouponByIdAndJwtResult.then((res) => {
          if (res.code === 200) {
            dialogFormVisible.value = false
            return ElMessage({
              showClose: true,
              message: "编辑商品成功",
              type: 'success',
            })
          } else {
            return ElMessage({
              showClose: true,
              message: res.message,
              type: 'error',
            })
          }
        })
      }
    } else {
      return ElMessage({
        showClose: true,
        message: '请检查参数',
        type: 'error',
      })
    }
  })
}

//页面清空返回
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogFormVisible.value = false
}

</script>
  
<style scoped>
.layout-container-demo .el-header {
  position: relative;
  background-color: var(--el-color-primary-light-7);
  color: var(--el-text-color-primary);
}

.layout-container-demo .el-aside {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-8);
}

.layout-container-demo .el-menu {
  border-right: none;
}

.layout-container-demo .el-main {
  padding: 0;
}

.layout-container-demo .toolbar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  right: 20px;
}
</style>
  